package com.jtpay.ysfproductionprocess.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.google.gson.Gson;
import com.jtpay.ysfproductionprocess.BuildConfig;
import com.jtpay.ysfproductionprocess.R;
import com.jtpay.ysfproductionprocess.http.ApiHelper;
import com.jtpay.ysfproductionprocess.service.UnionPayProductService;
import com.jtpay.ysfproductionprocess.utils.LogUtil;
import com.jtpay.ysfproductionprocess.utils.SharedPreferenceUtil;

import static com.jtpay.ysfproductionprocess.utils.ActivityHelper.startAlarmActivity;
import static com.jtpay.ysfproductionprocess.utils.PayContext.Debug;
import static com.jtpay.ysfproductionprocess.utils.PayContext.QR_PRODUCT_DELAY_TIME_DEF;

/**
 * Description:
 * File: BaseActivity.java
 * Author: Administrator
 * Create: 2018/08/14 10:03
 */
public abstract class BaseActivity extends AppCompatActivity {
    protected SharedPreferenceUtil sharedPreferenceUtil = new SharedPreferenceUtil();
    protected ApiHelper mApiHelper;
    protected Gson gson = new Gson();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setLayoutId());
        keepScreenLongLight();
        String versionName = Debug ? "(ce)" : "";
        setTitle(getString(R.string.product_program) + versionName);
        android.support.v7.app.ActionBar actionBar = this.getSupportActionBar();
        if (actionBar != null) {
            actionBar.setSubtitle(String.format("%s%s",
                    getString(R.string.version), BuildConfig.VERSION_NAME));
        }
        initView();
        initData();
    }

    /**
     * isAccessibilitySettingsOn check service is opened
     *
     * @param context Context
     * @return check result
     */
    protected boolean isAccessibilitySettingsOn(Context context) {
        int accessibilityEnabled = 0;
        final String service = getPackageName() + "/" + UnionPayProductService.class.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(context.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            showLog("Error ，productService to not found: " + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
        if (accessibilityEnabled == 1) {
            LogUtil.log("***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(context.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        LogUtil.log("***ACCESSIBILITY IS OPENED***");
                        return true;
                    }
                }
            } else {
                LogUtil.log("***ACCESSIBILITY IS CLOSED***");
            }
        }

        return false;
    }

    /**
     * doRequestPermissions
     */
    protected void doRequestPermissions() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        checkRequestPermissions();
    }

    /**
     * checkRequestPermissions result
     */
    protected void checkRequestPermissions() {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED
                || ActivityCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            showToast(getString(R.string.permission_denied_error));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, QR_PRODUCT_DELAY_TIME_DEF);
        }
    }

    /**
     * 屏幕常亮
     */
    protected void keepScreenLongLight() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    protected void openAccessibilityServiceSetting() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    protected void openProgramSetting() {
        Intent intent = new Intent()
                .setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                .setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(intent);
    }

    protected void setViewVisibility(final View view, final int visibility) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                view.setVisibility(visibility);
            }
        });
    }


    protected ApiHelper getApiHelper() {
        if (mApiHelper == null) {
            mApiHelper = ApiHelper.getInstance(this);
        }
        return mApiHelper;
    }

    protected void startAlarmSettingUI() {
        /*Intent alarmIntent = new Intent(AlarmClock.ACTION_SET_ALARM);
        startActivity(alarmIntent);*/
        startAlarmActivity();
    }

    protected abstract void initView();

    protected abstract void initData();

    protected abstract int setLayoutId();

    protected abstract void showLog(String content);

    protected abstract void showToast(String content);

    protected abstract void getServerTask();

    protected abstract void getServerAddress(String shopCode, String ysfAccount);
}
